/*******************************************************************************
 *
 *    Copyright (c) Baina Info Tech Co. Ltd
 *
 *    My_Ringtone
 *    
 *    MusicFileManager
 *    TODO File description or class description.
 *
 *    @author: zuochen
 *    @since:  2011-1-20
 *    @version: 1.0
 *
 ******************************************************************************/

package com.tools.ringtone.util;

import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.MediaScannerConnectionClient;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;

import com.tools.ringtone.soundfile.CheapSoundFile;

/**
 * MusicFileManager of My_Ringtone.
 * 
 * @author zuochen
 * 
 */

public class MusicFileManager {
	private static final String[] EXTERNAL_COLUMNS = new String[] {
			MediaStore.Audio.Media._ID, MediaStore.Audio.Media.DATA,
			MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.ARTIST,
			MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.IS_RINGTONE,
			MediaStore.Audio.Media.IS_ALARM,
			MediaStore.Audio.Media.IS_NOTIFICATION,
			MediaStore.Audio.Media.IS_MUSIC, MediaStore.Audio.Media.DURATION, };

	public static Cursor createCursorByPath(final Context aContext,
			final String aPath) {
		ArrayList<String> args = new ArrayList<String>();
		String selection;

		selection = "(";
		for (String extension : CheapSoundFile.getSupportedExtensions()) {
			args.add("%." + extension);
			if (selection.length() > 1) {
				selection += " OR ";
			}
			selection += "(_DATA LIKE ?)";
		}
		selection += ")";

		selection = "(" + selection + ") AND (_DATA NOT LIKE ?)";
		args.add("%espeak-data/scratch%");

		String filter = aPath;
		if (!TextUtils.isEmpty(filter)) {
			filter = "%" + filter + "%";
			selection = "(" + selection + " AND " + "(_DATA LIKE ?))";
			args.add(filter);
		}

		String[] argsArray = args.toArray(new String[args.size()]);

		Cursor c = aContext.getContentResolver().query(
				MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, EXTERNAL_COLUMNS,
				selection, argsArray, null);
		return c;
	}

	public static void scanFile(final Context aContext, final String aFile) {
		final MediaScannerConnection connection = new MediaScannerConnection(
				aContext, null);
		new MediaScannerConnection(aContext,
				new MediaScannerConnectionClient() {

					@Override
					public void onScanCompleted(String path, Uri uri) {

						connection.scanFile(aFile, null);

					}

					@Override
					public void onMediaScannerConnected() {

					}
				});
		connection.connect();
	}
}
